package org.jeecg.modules.system.controller.login;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CacheConstant;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.constant.SymbolConstant;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.base.service.BaseCommonService;
import org.jeecg.modules.system.controller.login.constant.Prompt;
import org.jeecg.common.message.UnicomSmsUtil;
import org.jeecg.modules.system.entity.SysRoleIndex;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.system.service.ISysDictService;
import org.jeecg.modules.system.service.ISysTenantService;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * 登录其他接口
 *
 * @author jiangtianyi
 * @version 1.2.2
 */
@Slf4j
@RestController
@RequestMapping("/sys")
public class LoginOthersController extends LoginHandler {

    /**
     * 获取当前用户信息
     *
     * @author jiangtianyi
     * @since 1.0
     */
    @GetMapping("/user/getUserInfo")
    public Result<JSONObject> currentUser(HttpServletRequest request) {
        // 登录用户信息
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // 根据用户名查询用户信息
        SysUser sysUser = sysUserService.getUserByName(loginUser.getUsername());
        // 自定义首页
        String version = request.getHeader(CommonConstant.VERSION);
        // 接口返回值修改，同步修改这里的判断逻辑
        SysRoleIndex roleIndex = sysUserService.getDynamicIndexByUserRole(loginUser.getUsername(), version);
        if (oConvertUtils.isNotEmpty(version) && roleIndex != null && oConvertUtils.isNotEmpty(roleIndex.getUrl())) {
            String homePath = roleIndex.getUrl();
            if (!homePath.startsWith(SymbolConstant.SINGLE_SLASH)) {
                homePath = SymbolConstant.SINGLE_SLASH + homePath;
            }
            sysUser.setHomePath(homePath);
        }
        JSONObject jsonObject = new JSONObject() {{
            this.put("userInfo", sysUser);
            this.put("sysAllDictItems", sysDictService.queryAllDictItems());
        }};
        return Result.OK(jsonObject);
    }

    /**
     * 用户属于多部门时，登陆成功后选择某个部门，作为操作痕迹
     *
     * @author jiangtianyi
     * @since 1.0
     */
    @PutMapping("/selectDepart")
    public Result<JSONObject> selectDepart(@RequestBody SysUser user) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // 更新当前操作用户所在部门
        sysUserService.updateUserDepart(loginUser.getUsername(), user.getOrgCode());
        SysUser sysUser = sysUserService.getUserByName(loginUser.getUsername());
        JSONObject jsonObject = new JSONObject() {{
            this.put("userInfo", sysUser);
        }};
        return Result.ok(jsonObject);
    }

    /**
     * 退出登录
     *
     * @author jiangtianyi
     * @since 1.0
     */
    @GetMapping(value = "/logout")
    public Result<String> logout(HttpServletRequest request) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if (sysUser != null) {
            // 登出日志
            baseCommonService.addLog("用户名: " + sysUser.getRealname() + ",退出成功！", CommonConstant.LOG_TYPE_1, null, sysUser);
            log.debug(" 用户名:  " + sysUser.getRealname() + ",退出成功！ ");
            // 清除登录Token缓存
            redisUtil.del(CommonConstant.PREFIX_USER_TOKEN + request.getHeader(CommonConstant.X_ACCESS_TOKEN));
            // 清除权限缓存
            redisUtil.del(CommonConstant.PREFIX_USER_SHIRO_CACHE + sysUser.getId());
            // 清除用户的缓存信息（包括部门信息），例如 sys:cache:user::<username>
            redisUtil.del(String.format("%s::%s", CacheConstant.SYS_USERS_CACHE, sysUser.getUsername()));
            // 调用shiro logout
            SecurityUtils.getSubject().logout();
            return Result.ok(Prompt.LOGOUT_SUCCESS_PROMPT);
        }
        return Result.error(Prompt.LOGOUT_ERROR_PROMPT);
    }

    /**
     * 生成图形验证码
     *
     * @param checkKey 验证码Key
     * @author jiangtianyi
     * @since 1.0
     */
    @GetMapping("/randomImage/{checkKey}")
    public Result<String> generateGraphicCode(@PathVariable("checkKey") String checkKey) {
        String base64 = this.graphicCodeFormula(checkKey);
        return Result.OK(StringUtils.EMPTY, base64);
    }

    public LoginOthersController(RedisUtil redisUtil, UnicomSmsUtil unicomSmsUtil, RsaEncryptProperty rsaEncryptProperty, BaseCommonService baseCommonService, ISysDictService sysDictService, ISysTenantService sysTenantService, ISysUserService sysUserService, ISysDepartService sysDepartService, RedisTemplate<String, Object> redisTemplate) {
        super(redisUtil, unicomSmsUtil, rsaEncryptProperty, baseCommonService, sysDictService, sysTenantService, sysUserService, sysDepartService, redisTemplate);
    }
}
